package com.css.fxfzaqbz.modules.assess1.service.impl;

import com.css.fxfzaqbz.base.upload.controller.AttachmentController;
import com.css.fxfzaqbz.base.upload.entity.AttachmentInfoEntity;
import com.css.fxfzaqbz.base.upload.repository.AttachmentInfoRepository;
import com.css.fxfzaqbz.constants.YNEnum;
import com.css.fxfzaqbz.modules.assess1.entity.ReportHuiXianEntity;
import com.css.fxfzaqbz.modules.assess1.repository.LittleRepotrRepository;
import com.css.fxfzaqbz.modules.assess1.service.LittleRepotrService;
import com.css.fxfzaqbz.modules.assess1.entity.LittleReport;
import com.css.fxfzaqbz.modules.assess1.vo.LittleReportVO;
import com.css.fxfzaqbz.modules.assess1.vo.SaveReportVO;
import com.css.fxfzaqbz.modules.assess1.vo.SubmitLittleRepoetVO;
import com.css.fxfzaqbz.modules.assess2.controller.ProductController;
import com.css.fxfzaqbz.modules.data.repository.ReportTemplateRepository;
import com.css.fxfzaqbz.util.PlatformDateUtils;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import com.css.fxfzaqbz.util.PlatformSessionUtils;
import com.css.fxfzaqbz.util.UUIDGenerator;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author y1fan
 * @description
 */
@Service
public class LittleRepotrServiceImpl implements LittleRepotrService {


    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;

    @Resource
    private LittleRepotrRepository littleRepotrRepository;

    @Resource
    private AttachmentController attachmentController;


    @Value("${image.localDir}")
    private String localDir;

    @Override
    public void save(SaveReportVO saveReportVO) throws IOException {
        List<String> list = attachmentController.uploadFileLittleReport(saveReportVO.getFile());
        if (!PlatformObjectUtils.isEmpty(list)) {
            for (String s : list) {
                LittleReport littleReport = new LittleReport();
                littleReport.setId(UUIDGenerator.getUUID());
                littleReport.setIaId(saveReportVO.getIaId());
                AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(s);
                LocalDateTime now = LocalDateTime.now();
                String nowFormat = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                littleReport.setName(attach.getAttachName() + nowFormat);
                littleReport.setStatus(YNEnum.N.toString());
                littleReport.setDelFlag(YNEnum.N.toString());
                littleReport.setCraeteTime(PlatformDateUtils.getCurrentTimestamp());
                littleReport.setCreateUser(PlatformSessionUtils.getUserId());
                littleReport.setIaId(saveReportVO.getIaId());
                littleReport.setAttachId(s);
                littleReport.setNumber(saveReportVO.getNumber());
                littleRepotrRepository.save(littleReport);
            }
        }


    }

    @Resource
    private ReportTemplateRepository reportTemplateRepository;

    @Override
    public Map<String, Object> getAll(LittleReportVO littleReportVO) {
        Map<String, Object> map = new HashMap();
        List<ReportHuiXianEntity> reportHuiXianByIaIdAndNumber = reportTemplateRepository.getReportHuiXianByIaIdAndNumber(littleReportVO.getIaId(), littleReportVO.getNumber());
        List<LittleReport> littleReports = littleRepotrRepository.getAll(littleReportVO);
        if (PlatformObjectUtils.isEmpty(reportHuiXianByIaIdAndNumber)) {
            map.put("reportHuiXian", null);
            map.put("littleReports", littleReports);
        } else {
            map.put("reportHuiXian", reportHuiXianByIaIdAndNumber.get(0));
            map.put("littleReports", littleReports);
        }


        return map;
    }

    @Override
    public void submit(SubmitLittleRepoetVO submitLittleRepoetVO) {
        littleRepotrRepository.submit(submitLittleRepoetVO);
    }

    @Override
    public Map<String, Object> getLittleReport(String iaId) {
        List<LittleReport> littleReports = littleRepotrRepository.getLittleReport(iaId);
        List<LittleReport> littleReportList0 = new ArrayList<>();
        List<LittleReport> littleReportList1 = new ArrayList<>();
        List<LittleReport> littleReportList2 = new ArrayList<>();
        List<LittleReport> littleReportList = new ArrayList<>();

        for (LittleReport littleReport : littleReports) {
            if (littleReport.getStatus().equals("1") && littleReport.getNumber().equals("0")) {
                littleReportList0.add(littleReport);
                break;
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList0)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("2") && littleReport.getNumber().equals("0")) {
                    littleReportList0.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList0)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("0") && littleReport.getNumber().equals("0")) {
                    littleReportList0.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList0)) {
            LittleReport littleReport = new LittleReport();
            littleReport.setId(UUIDGenerator.getUUID());
            littleReport.setNumber("0");
            littleReport.setStatus(null);
            littleReportList0.add(littleReport);
        }


        for (LittleReport littleReport : littleReports) {
            if (littleReport.getStatus().equals("1") && littleReport.getNumber().equals("1")) {
                littleReportList1.add(littleReport);
                break;
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList1)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("2") && littleReport.getNumber().equals("1")) {
                    littleReportList1.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList1)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("0") && littleReport.getNumber().equals("1")) {
                    littleReportList1.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList1)) {
            LittleReport littleReport = new LittleReport();
            littleReport.setId(UUIDGenerator.getUUID());
            littleReport.setNumber("1");
            littleReport.setStatus(null);
            littleReportList1.add(littleReport);
        }


        for (LittleReport littleReport : littleReports) {
            if (littleReport.getStatus().equals("1") && littleReport.getNumber().equals("2")) {
                littleReportList2.add(littleReport);
                break;
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList2)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("2") && littleReport.getNumber().equals("2")) {
                    littleReportList2.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList2)) {
            for (LittleReport littleReport : littleReports) {
                if (littleReport.getStatus().equals("0") && littleReport.getNumber().equals("2")) {
                    littleReportList2.add(littleReport);
                    break;
                }
            }
        }
        if (PlatformObjectUtils.isEmpty(littleReportList2)) {
            LittleReport littleReport = new LittleReport();
            littleReport.setId(UUIDGenerator.getUUID());
            littleReport.setNumber("2");
            littleReport.setStatus(null);
            littleReportList2.add(littleReport);
        }
        littleReportList.addAll(littleReportList0);
        littleReportList.addAll(littleReportList1);
        littleReportList.addAll(littleReportList2);




        Map<String, Object> map = new HashMap();
        List<ReportHuiXianEntity> reportHuiXianByIaIdAndNumber = reportTemplateRepository.getReportHuiXianByIaIdAndNumber(iaId, "4");
        if (PlatformObjectUtils.isEmpty(reportHuiXianByIaIdAndNumber)) {
            map.put("reportHuiXian", null);
            map.put("littleReportList", littleReportList);
        } else {
            map.put("reportHuiXian", reportHuiXianByIaIdAndNumber.get(0));
            map.put("littleReportList", littleReportList);
        }
        return map;

    }

    @Override
    public void delete(String id) {
        littleRepotrRepository.delete(id);
    }

    @Override
    public boolean check(String iaId, String number) {
        return littleRepotrRepository.check(iaId, number);
    }

    @Override
    public void back(String id) {
        littleRepotrRepository.back(id);
    }

    @Override
    public LittleReport getById(String id) {
        return littleRepotrRepository.getById(id);
    }

    @Override
    public void pdf(HttpServletResponse response, String sign) throws IOException {
        InputStream fis = null;
        OutputStream out = null;
        String taskName = null;
        String localFilePath =null;
        try {
//        String localFilePath=localDir + File.separator +"temp"+File.separator + "aaa.pdf";
            if ("0".equals(sign)) {
//                fis = ProductController.class.getClassLoader().getResourceAsStream("template/[报告管理流程说明].pdf");
                localFilePath = "/usr/zhaoshuai/aqbz/template/[报告管理流程说明].pdf";
                taskName = "[报告管理流程说明].pdf";
            }
            if ("1".equals(sign)) {
                localFilePath = "/usr/zhaoshuai/aqbz/template/地震环境及监测能力分析-说明.pdf";
                taskName = "地震环境及监测能力分析-说明.pdf";
            }
            if ("2".equals(sign)) {
                localFilePath = "/usr/zhaoshuai/aqbz/template/地震灾害风险排查及建议-说明.pdf";
                taskName = "地震灾害风险排查及建议-说明.pdf";
            }
            if ("3".equals(sign)) {
                localFilePath = "/usr/zhaoshuai/aqbz/template/房屋地震灾害分析评估-说明.pdf";
                taskName = "房屋地震灾害分析评估-说明.pdf";
            }
            File file = new File(localFilePath);
            fis = new FileInputStream(file);
            StringBuilder fileName = new StringBuilder();
            fileName.append(taskName + "_");
            LocalDateTime now = LocalDateTime.now();
            String nowFormat = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            fileName.append("(").append(nowFormat).append(").pdf");
            // 设置响应头
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            // 获取输出流
            out = response.getOutputStream();
            // 将PDF内容写给前端
            IOUtils.copy(fis, out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(out);
        }
    }


    public static String PDFToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while (len != -1) {
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getFileBase64StrByLocalFile(String localFilePath) {

        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(localFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(data));
    }
}
